package com.jun.controller.admin;

import com.jun.pojo.admin.SysAdmin;
import com.jun.pojo.vo.R;
import com.jun.service.SysAdminService;
import com.jun.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/sysAdmin")
public class SysAdminController {

  @Autowired
  private SysAdminService sysAdminService;

  @GetMapping
  public String test() {
    return "test success";
  }

  /**
   * 管理员登录
   * @param sysAdmin 接收参数的实体类
   * @return 返回管理员信息和token令牌
   */
  @PostMapping("/login")
  public R login(@Validated @RequestBody SysAdmin sysAdmin) {
    SysAdmin sa = sysAdminService.selectByAdminName(sysAdmin);

    if (sa != null) {
      Map<String, Object> result = new HashMap<>(2);
      result.put("sysAdmin", sa);
      result.put("token", JwtUtil.createJwt(sa));
      return new R(result);
    }

    return new R().error();
  }

  /**
   * 检验是否已经登录
   * @param token 令牌
   * @return 返回是否已登录
   */
  @PostMapping("/isLogged")
  public R logged(@RequestBody String token) {
    try {
      String sub = JwtUtil.obtainSubject(token);
      return new R(sub);
    } catch (Exception e) {
      e.printStackTrace();
      return new R().error();
    }
  }


}
